package com.cw.jeeyt.service.impl.api;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.cw.jeeyt.common.Order;
import com.cw.jeeyt.common.enums.EnumYn;
import com.cw.jeeyt.service.bo.api.ApiFacadeMethodBo;
import com.cw.jeeyt.service.bo.api.ApiFacadeObjBo;
import com.cw.jeeyt.service.bo.api.ApiFacadeParam;
import com.cw.jeeyt.service.bo.security.SecurityUserBo;
import com.cw.jeeyt.core.util.SessionUtil;
import com.cw.jeeyt.dao.intf.api.ApiFacadeMethodDao;
import com.cw.jeeyt.dao.model.api.ApiFacadeMethodDo;
import com.cw.jeeyt.service.intf.api.ApiFacadeMethodService;
import com.cw.jeeyt.service.intf.api.ApiFacadeObjService;
import com.cw.jeeyt.service.converter.api.ApiFacadeMethodConverter;
import com.cw.lang.mybatis.dto.PageInfo;

/**
 * api接口方法业务实现类
 *
 *
 * @author chenw
 * @version 1.0.0
 */
@Service
public class ApiFacadeMethodServiceImpl implements ApiFacadeMethodService {

    private static final Logger logger = LoggerFactory.getLogger(ApiFacadeMethodServiceImpl.class);
    @Autowired
    private ApiFacadeMethodDao apiFacadeMethodDao;//api接口方法数据库操作接口
    @Autowired
    private ApiFacadeObjService apiFacadeObjService;//接口参数对象业务接口

    /**
     * 查询所有api接口方法
     */
    @Override
    public List<ApiFacadeMethodBo> queryApiFacadeMethodList() throws Exception {
        return ApiFacadeMethodConverter.doList2BoList(apiFacadeMethodDao.queryApiFacadeMethodList());
    }

    /**
     * 分页查询api接口方法
     *
     * @param apiFacadeMethodBo
     * @param pageNo
     * @param pageSize
     * @return
     * @throws Exception
     */
    @Override
    public PageInfo<ApiFacadeMethodBo> queryByPage(ApiFacadeMethodBo apiFacadeMethodBo, Integer pageNo,
        Integer pageSize, Order order) throws Exception {
        PageInfo<ApiFacadeMethodDo> pageInfo = apiFacadeMethodDao.queryByPage(
            ApiFacadeMethodConverter.bo2Do(apiFacadeMethodBo), pageNo, pageSize, order);
        return new PageInfo<>(pageInfo, ApiFacadeMethodConverter.doList2BoList(pageInfo.getList()));
    }

    /**
     * 根据主键查寻api接口方法信息
     *
     * @param id
     * @return
     */
    @Override
    public ApiFacadeMethodBo getApiFacadeMethodById(Long id) throws Exception {

        if (null == id) {
            logger.error("--主键id为空--");
            return null;
        }
        return ApiFacadeMethodConverter.do2Bo(apiFacadeMethodDao.getById(id));
    }

    /**
     * 新增api接口方法
     *
     * @param apiFacadeMethodBo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer insert(ApiFacadeMethodBo apiFacadeMethodBo) throws Exception {

        if (apiFacadeMethodBo == null) {
            logger.error("api接口方法为空");
            return null;
        }
        SecurityUserBo userVo = SessionUtil.getSessionUser();
        if (userVo == null) {
            logger.error("用户未登录");
            throw new Exception("用户未登录");
        }
        ApiFacadeMethodDo apiFacadeMethod = ApiFacadeMethodConverter.bo2Do(apiFacadeMethodBo);
        apiFacadeMethod.setCreateBy(userVo.getId());
        apiFacadeMethod.setCreateDate(new Date());
        apiFacadeMethod.setUpdateBy(userVo.getId());
        apiFacadeMethod.setUpdateDate(new Date());
        Integer result = apiFacadeMethodDao.insert(apiFacadeMethod);
        return result;
    }

    /**
     * 新增api接口方法不为空的字段
     *
     * @param apiFacadeMethodBo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer insertSelective(ApiFacadeMethodBo apiFacadeMethodBo) throws Exception {

        if (apiFacadeMethodBo == null) {
            logger.error("api接口方法为空");
            return null;
        }
        SecurityUserBo userVo = SessionUtil.getSessionUser();
        if (userVo == null) {
            logger.error("用户未登录");
            throw new Exception("用户未登录");
        }
        ApiFacadeMethodDo apiFacadeMethod = ApiFacadeMethodConverter.bo2Do(apiFacadeMethodBo);
        apiFacadeMethod.setCreateBy(userVo.getId());
        apiFacadeMethod.setCreateDate(new Date());
        apiFacadeMethod.setUpdateBy(userVo.getId());
        apiFacadeMethod.setUpdateDate(new Date());
        Integer result = apiFacadeMethodDao.insertSelective(apiFacadeMethod);
        return result;
    }

    /**
     * 更新api接口方法
     *
     * @param apiFacadeMethodBo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(ApiFacadeMethodBo apiFacadeMethodBo) throws Exception {

        if (apiFacadeMethodBo == null) {
            logger.error("api接口方法为空");
            return;
        }
        SecurityUserBo userVo = SessionUtil.getSessionUser();
        if (userVo == null) {
            logger.error("用户未登录");
            throw new Exception("用户未登录");
        }
        ApiFacadeMethodDo apiFacadeMethod = ApiFacadeMethodConverter.bo2Do(apiFacadeMethodBo);
        apiFacadeMethod.setUpdateBy(userVo.getId());
        apiFacadeMethod.setUpdateDate(new Date());

        apiFacadeMethodDao.update(apiFacadeMethod);
    }

    /**
     * 更新api接口方法不为空的字段
     *
     * @param apiFacadeMethodBo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateSelective(ApiFacadeMethodBo apiFacadeMethodBo) throws Exception {

        if (apiFacadeMethodBo == null) {
            logger.error("api接口方法为空");
            return;
        }
        SecurityUserBo userVo = SessionUtil.getSessionUser();
        if (userVo == null) {
            logger.error("用户未登录");
            throw new Exception("用户未登录");
        }
        ApiFacadeMethodDo apiFacadeMethod = ApiFacadeMethodConverter.bo2Do(apiFacadeMethodBo);
        apiFacadeMethod.setUpdateBy(userVo.getId());
        apiFacadeMethod.setUpdateDate(new Date());

        apiFacadeMethodDao.updateSelective(apiFacadeMethod);
    }

    /**
     * 删除api接口方法
     *
     * @param apiFacadeMethodBo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(ApiFacadeMethodBo apiFacadeMethodBo) throws Exception {

        if (apiFacadeMethodBo == null) {
            logger.error("api接口方法为空");
            return;
        }
        apiFacadeMethodDao.delete(ApiFacadeMethodConverter.bo2Do(apiFacadeMethodBo));
    }

    /**
     * 根据接口文档id查询接口方法
     */
    @Override
    public List<ApiFacadeMethodBo> queryListByDocId(Long docId) throws Exception {
        if (docId == null) {
            logger.error("api接口文档id为空");
            return null;
        }
        List<ApiFacadeMethodBo> facadeMethodBos = ApiFacadeMethodConverter.doList2BoList(
            apiFacadeMethodDao.queryListByDocId(docId));
        if (facadeMethodBos != null && !facadeMethodBos.isEmpty()) {
            for (ApiFacadeMethodBo facadeMethodBo : facadeMethodBos) {
                //封装接口方法对应的请求对象、响应对象、公共请求对象、公共响应对象
                loadObjInfo(facadeMethodBo);
            }
        }
        return facadeMethodBos;
    }

    /**
     * 封装接口方法对应的请求对象、响应对象、公共请求对象、公共响应对象
     *
     * @param apiFacadeMethod
     * @throws Exception
     * @throws NumberFormatException
     */
    private void loadObjInfo(ApiFacadeMethodBo apiFacadeMethod) throws NumberFormatException, Exception {
        List<ApiFacadeObjBo> requestList = new ArrayList<ApiFacadeObjBo>();
        List<ApiFacadeObjBo> publicRequestList = new ArrayList<ApiFacadeObjBo>();
        List<ApiFacadeObjBo> responseList = new ArrayList<ApiFacadeObjBo>();
        List<ApiFacadeObjBo> publicResponseList = new ArrayList<ApiFacadeObjBo>();
        String requestIds = apiFacadeMethod.getRequestIds();
        String responseIds = apiFacadeMethod.getResponseIds();
        if (!StringUtils.isEmpty(requestIds)) {
            String[] requestIdList = requestIds.split(",");
            for (String requestId : requestIdList) {
                ApiFacadeObjBo apiFacadeObj = apiFacadeObjService.getApiFacadeObjById(Long.parseLong(requestId));
                if (apiFacadeObj != null) {
                    String isPublicObj = apiFacadeObj.getIsPublicObj();
                    if (EnumYn.Y.getCode()
                        .equals(isPublicObj)) {
                        publicRequestList.add(apiFacadeObj);
                    } else {
                        requestList.add(apiFacadeObj);
                    }
                }
            }
        }
        if (!StringUtils.isEmpty(responseIds)) {
            String[] responseIdList = responseIds.split(",");
            for (String responseId : responseIdList) {
                ApiFacadeObjBo apiFacadeObj = apiFacadeObjService.getApiFacadeObjById(Long.parseLong(responseId));
                if (apiFacadeObj != null) {
                    String isPublicObj = apiFacadeObj.getIsPublicObj();
                    if (EnumYn.Y.getCode()
                        .equals(isPublicObj)) {
                        publicResponseList.add(apiFacadeObj);
                    } else {
                        responseList.add(apiFacadeObj);
                    }
                }
            }
        }
        apiFacadeMethod.setRequestList(requestList);
        apiFacadeMethod.setPublicRequestList(publicRequestList);
        apiFacadeMethod.setResponseList(responseList);
        apiFacadeMethod.setPublicResponseList(publicResponseList);
    }

    /**
     * 批量保存接口文档方法信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveApiFacadeMethodBat(List<ApiFacadeMethodBo> apiFacadeMethodList) throws Exception {

        SecurityUserBo userVo = SessionUtil.getSessionUser();
        if (userVo == null) {
            logger.error("用户未登录");
            throw new Exception("用户未登录");
        }
        if (apiFacadeMethodList != null && !apiFacadeMethodList.isEmpty()) {
            List<ApiFacadeMethodDo> apiMethodList = new ArrayList<ApiFacadeMethodDo>();
            for (ApiFacadeMethodBo afm : apiFacadeMethodList) {
                ApiFacadeMethodDo apiFacadeMethod = ApiFacadeMethodConverter.bo2Do(afm);
                apiFacadeMethod.setCreateBy(userVo.getId());
                apiFacadeMethod.setCreateDate(new Date());
                apiFacadeMethod.setUpdateBy(userVo.getId());
                apiFacadeMethod.setUpdateDate(new Date());
                apiMethodList.add(apiFacadeMethod);
            }
            apiFacadeMethodDao.insertBat(apiMethodList);
        }
    }

    /**
     * 获取请求、响应参数集合
     */
    @Override
    public List<ApiFacadeParam> getParamList(String paramData) {

        List<ApiFacadeParam> paramList = new ArrayList<ApiFacadeParam>();
        if (!StringUtils.isEmpty(paramData)) {
            String[] requestDatas = paramData.split(";");
            if (requestDatas != null && requestDatas.length > 0) {
                for (String rd : requestDatas) {
                    String[] params = rd.split("##");
                    if (params != null && params.length > 0) {
                        ApiFacadeParam apiFacadeParam = new ApiFacadeParam();
                        String paramType = params[1];
                        if (!StringUtils.isEmpty(paramType)) {
                            paramType = paramType.replace("<", "&lt;")
                                .replace(">", "&gt;");
                            apiFacadeParam.setParamJavaType(paramType);
                        }
                        apiFacadeParam.setParamCode(params[0]);
                        apiFacadeParam.setIsRequired(params[2]);
                        apiFacadeParam.setMaxLength(params[3]);
                        apiFacadeParam.setParamDesc(params[4]);
                        apiFacadeParam.setParamDemo(params[5]);
                        paramList.add(apiFacadeParam);
                    }
                }
            }
        }
        return paramList;
    }
}
